<?php
namespace app\models;

use Yii;
use yii\base\Model;

/**
 * 前台用户登录表单
 *
 * Class UserLoginForm
 * @package app\models
 *
 * @property User $user 用户信息
 */
class UserLoginForm extends Model
{
    public $mobile;
    public $password;
    public $rememberMe = true;

    /* @var $_user false|User */
    private $_user = false;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['mobile', 'password'], 'required'],
            ['rememberMe', 'boolean'],
            ['mobile', 'exist', 'targetClass'=>User::className(), 'message'=>'此手机号码未注册过。'],
            ['password', 'validatePassword'],
        ];
    }

    /**
     * 验证密码
     * @param string $attribute
     * @param mixed $params
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, '用户名或密码错误。');
            }
        }
    }

    /**
     * 用户登录
     * @return boolean
     */
    public function login()
    {
        if ($this->validate()) {
            $this->_user->generateAuthKey();
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
        }
        return false;
    }

    /**
     * 根据登录信息返回用户Model
     * @return false|User
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = User::find()->where(['status'=>[User::STATUS_ACTIVE, User::STATUS_STOPED], 'mobile'=>$this->mobile])->one();
            if (!empty($this->_user) && $this->_user->status == User::STATUS_STOPED) {
                $this->addError('mobile', '用户账号已停用。');
            }
        }
        return $this->_user;
    }
}
